package com.jzsec.tzdslog;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ObjectMapper;

import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TzdsLoginProc {
	private static ObjectMapper mapper = new ObjectMapper();
	private static int errCnt = 0;
	private static int loginCnt = 0;
	private static String localIp = "";
	private static FileOutputStream lgout = null;
	private static OutputStreamWriter lgouts = null;
	private static BufferedWriter lgwriterBuf = null;
	private static FileOutputStream uflgout = null;
	private static OutputStreamWriter uflgouts = null;
	private static BufferedWriter uflgwriterBuf = null;
	private static String logdate = null;
	private static String srcDirPath = "";
	private static String dstDirpath = ".";
	private static String ufdstDirpath = ".";
	private static String nowDatePrefix = "";
	private static SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
	private static String filePrefix = "";
	private static int isRzRq = 0;

	public static void main(String[] args) throws ParseException {

		File file = null;
		FileInputStream fis = null;
		try {
			file = new File("D:/B/loginbymargin.log");
			fis = new FileInputStream(file);
			InputStreamReader ins = new InputStreamReader(fis);
			BufferedReader readBuf = new BufferedReader(ins);
			String line = null;
			while ((line = readBuf.readLine()) != null) {
				procLog(line);
			}
		} catch (FileNotFoundException e) {
			System.out.println(file + " not exsist.");
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private static String procLog(String line) throws ParseException, IOException {
		String clientIp = "";
		LogModel log = new LogModel();
		Map map = new HashMap();
		Map unifyLog = new HashMap();
		initLoginLog(unifyLog);

		log.setAppType("tzdsAccess");
		log.setCid("0x1C030000");
		log.setMid("0x1C030001");
		log.setName("tzds");
		log.setIndicator(map);


		Pattern p = Pattern.compile("(\\S+)\\s");
		Matcher m = p.matcher(line);
		if (m.find()) {
			clientIp = m.group(0);
			log.setIp(localIp);
		}


		try {
			String timeStr = line.substring(line.indexOf("[") + 1, line.lastIndexOf("]")).replace("]", "");
			SimpleDateFormat sdf = new SimpleDateFormat("d/MMM/yyyy:K:m:s Z", Locale.ENGLISH);
			SimpleDateFormat sdfnew = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date d2 = null;
			try {
				d2 = sdf.parse(timeStr.trim());
			} catch (ParseException e) {
				return "";
			}
			timeStr = sdfnew.format(d2);
			log.setTime_stamp(Long.toString(d2.getTime()));
			map.put("accessTime", timeStr);


			String method = line.substring(line.indexOf("]") + 1, line.length());
			Pattern pm = Pattern.compile("^\\s\"(.*?)\"\\s(\\d+)\\s(\\d+)\\s\".*?\"\\s\"(.*?)\"\\s\"(.*?)\"\\s\"(.*?)\"\\s(.*?)\\s(.*?)\\s(.*?)\\s(.*?)$");
			Matcher mm = pm.matcher(method);
			if (mm.find()) {
				map.put("httpInfo", mm.group(1));
				map.put("httpRetCode", mm.group(2));
				map.put("contentLength", mm.group(3));
				map.put("agentInfo", mm.group(5));
				map.put("clientIp", getClientIp(mm.group(6), clientIp));
				map.put("upstream_rsp_time", mm.group(8));
				map.put("request_time", mm.group(10));
				procRequestParams(map, mm.group(4));
				procLoginLog(unifyLog, map, log.getTime_stamp());

				System.out.println(mapper.writeValueAsString(unifyLog));
			}
		} catch (Exception e) {
//			System.out.println(e);
			e.printStackTrace();
			errCnt++;
			return "";
		}


		return "";
	}

	private static String getClientIp(String proxyIP, String clientIP) {
		if (proxyIP.equals("-")) {
			return clientIP.replace(" ", "");
		}
		if (clientIP.contains("10.10") || clientIP.contains("10.13") || clientIP.contains("10.198")) {
			return proxyIP;
		}
		return clientIP.replace(" ", "");
	}

	private static void procRequestParams(Map map, String params) {
		if (params.equals("-")) {
			return;
		}
		String param = params.replace("\\x22", "\"");
		JSONObject jsonObj = JSON.parseObject(param.trim());
		for (Map.Entry<String, Object> entry : jsonObj.entrySet()) {
			if (((String)entry.getKey()).equals("op_station")) {
				String[] station = ((String)entry.getValue()).split("\\|");
				for (int j = 0; j < station.length; j++) {
					String[] stationItem = station[j].contains("mac") ? station[j].split(":", 2) : station[j].split(":");
					if (stationItem.length == 2)
						if (stationItem[0].equals("clientip")) {
							map.put("opstat_clientip", stationItem[1]);
						} else {
							map.put(stationItem[0], stationItem[1]);
						}
				}  continue;
			}
			if (((String)entry.getKey()).equals("password"))
				continue;
			if (((String)entry.getKey()).equals("login_info")) {
				map.put("input_content", ((JSONObject)entry.getValue()).getString("input_content")); continue;
			}
			map.put(entry.getKey(), entry.getValue());
		}
	}



	private static void initLoginLog(Map map) {
		map.put("brokerName", "九州证券");
		map.put("branchNo", "");
		map.put("branchName", "");
		map.put("fundId", "");
		map.put("secName", "");
		map.put("operDate", "");
		map.put("operTime", "");
		map.put("operDesc", "");
		map.put("entrustWay", "");
		map.put("entrustWayName", "手机炒股");
		map.put("appTypeName", "");
		map.put("appType", "");
		map.put("appID", "TZDS");
		map.put("appIDName", "投资大师");
		map.put("appVer", "");
		map.put("computerName", "");
		map.put("clientIP", "");
		map.put("mac", "");
		map.put("cpuNO", "");
		map.put("hddCode", "");
		map.put("hddLvInfo", "");
		map.put("imei", "");
		map.put("uuid", "");
		map.put("guid", "");
		map.put("osVer", "");
		map.put("mobilePhone", "");
		map.put("phone", "");
		map.put("bpRetCode", "");
		map.put("status", Integer.valueOf(0));
		map.put("timeStamp", "");
	}

	private static void procLoginLog(Map unify, Map map, String time_stamp) {
		unify.put("timeStamp", time_stamp);
		unify.put("branchNo", (map.get("branch_no") != null) ? map.get("branch_no") : "");
		unify.put("fundId", (map.get("custid") != null) ? map.get("custid") : map.get("input_content"));
		unify.put("operDate", (map.get("accessTime") != null) ? ((String) map.get("accessTime")).split(" ")[0] : "");
		unify.put("operTime", (map.get("accessTime") != null) ? ((String) map.get("accessTime")).split(" ")[1] : "");
		unify.put("entrustWay", (map.get("entrust_way") != null) ? map.get("entrust_way") : "");
		unify.put("appType", (map.get("deviceType") != null && map.get("deviceType").equals("IOS")) ? "MI" : "MA");
		if (unify.get("appType").equals("MI")) {
			unify.put("appTypeName", "移动IOS终端");
		} else {
			unify.put("appTypeName", "移动Android终端");
		}
		unify.put("appVer", (map.get("ver") != null) ? map.get("ver") : map.get("appVer"));
		unify.put("computerName", (map.get("computername") != null) ? map.get("computername") : "");
		unify.put("clientIP", (map.get("clientIp") != null) ? map.get("clientIp") : "");
		unify.put("mac", (map.get("mac") != null) ? map.get("mac") : "");
		unify.put("imei", (map.get("imei") != null) ? map.get("imei") : "");
		unify.put("uuid", (map.get("udid") != null) ? map.get("udid") : map.get("deviceCode"));
		unify.put("osVer", (map.get("agentInfo") != null) ? map.get("agentInfo") : "");
		unify.put("mobilePhone", (map.get("mobilephone") != null) ? map.get("mobilephone") : "");
	}

}
